<?php
ini_set('error_reporting', 6143);
ini_set('display_errors','2');
define('IN_LC', true);
define('MM_ID', 3);
ini_set('wincache.fcenabled','0');

include_once("validate.php");

// This is a minimum example of using the class
include_once("includes/feedwriter/FeedWriter.php");
include_once("includes/feedwriter/FeedItem.php");

global $www_path, $properties, $lang, $db;


if(isset ($_GET['feed']) && $_GET['feed'] == 'champs')
{

        //Creating an instance of FeedWriter class.
        $feed = new FeedWriter(RSS2);
        //Setting the channel elements
        //Use wrapper functions for common channel elements
        $feed->setTitle('GRC League Control: Latest Championships Feed');
        $feed->setLink($www_path . 'feeds.php?feed=champs');
        $feed->setDescription('All the latest Championships from GRC.');

        //Image title and link must match with the 'title' and 'link' channel elements for valid RSS 2.0
        $feed->setImage('GRC Logo',$www_path . 'feeds.php?feed=champs',$www_path . '/skins/default/images/email_grc_logo.jpg');

        $data=Array();

        $query = "SELECT c_title, c_id, c_introText, c_firstRace, g_name, c_logoURL
                    FROM " . CHAMPIONSHIPS_TABLE . ", " . GAMES_TABLE . "
                    WHERE c_openSignUps = 1 AND c_lastRace > NOW() AND c_enabled = 1 AND c_game = g_id
                    ORDER BY c_firstRace DESC";

        $result = $db->sql_query($query);
        while($row = $db->sql_fetchrow($result))
        {
            $row = formatArrayOutput($row);

            //need to figure out the dates.
            $postDate = strtotime($row['c_firstRace']);
            $postDate = strtotime("-{$properties['cron_openeventstime']} days", $postDate);

            $description = '';

            if($row['c_logoURL']!='')
                $description = "<img src=\"{$www_path}{$row['c_logoURL']}\"/> <br/><br/>";

            $startDate = date("l F j, Y, g:i a",strtotime($row['c_firstRace']));

            $description .= "{$lang['Game']}: {$row['g_name']}. <br/>";
            $description .= "{$lang['firstRace']}: {$startDate}. <br/><br/>";
            $description .= $row['c_introText'];

            //Create an empty FeedItem
            $newItem = $feed->createNewItem();

            //Add elements to the feed item
            $newItem->setTitle(sprintf($lang['IntroducingObject'],$row['c_title']));
            $newItem->setLink($www_path . "championships.php?mode=entrants&id={$row['c_id']}");
            $newItem->setDate($postDate);
            $newItem->setDescription($description);

            //Now add the feed item
            $feed->addItem($newItem);
        }

        //OK. Everything is done. Now genarate the feed.
        $feed->genarateFeed();

}
else if(isset ($_GET['feed']) && $_GET['feed'] == 'events')
{

        //Creating an instance of FeedWriter class.
        $feed = new FeedWriter(RSS2);
        //Setting the channel elements
        //Use wrapper functions for common channel elements
        $feed->setTitle('GRC League Control: Latest Events Feed');
        $feed->setLink($www_path . 'feeds.php?feed=events');
        $feed->setDescription('All up and coming events that are now available for drivers to sign up to at GRC.');

        //Image title and link must match with the 'title' and 'link' channel elements for valid RSS 2.0
        $feed->setImage('GRC Logo',$www_path . 'feeds.php?feed=events',$www_path . '/skins/default/images/email_grc_logo.jpg');

        $data=Array();

        $queryEventInfo = "SELECT e_id, c_id, c_title, c_introText, e_title, e_description, t_fullTitle, t_location, t_logo, g_name, l_name, MAX(ed_date) as latedate
                           FROM " . CHAMPIONSHIPS_TABLE . ", " . DIVISIONS_TABLE . ", " . TRACKS_TABLE . ", " .
                                  EVENTS_TABLE . ", " . EVENTDATES_TABLE . ", " . LICENSES_TABLE . ", " . GAMES_TABLE . "
                           WHERE d_champid = c_id AND c_license = l_id AND g_id = c_game AND ed_event = e_id AND e_championship = c_id AND
                                 e_track = t_id AND c_enabled = 1 AND e_openSignUps = 1 AND ed_date > NOW()
                           GROUP BY e_id
                           ORDER BY latedate DESC";

        $result = $db->sql_query($queryEventInfo);
        while($row = $db->sql_fetchrow($result))
        {
            $data[$row['e_id']] = $row;
            $data[$row['e_id']]['dcount'] = 0;
        }

        $queryDateInfo = "SELECT e_id, ed_date, d_id, d_order, d_title, ed_capacity
                          FROM " . EVENTDATES_TABLE . ", " . EVENTS_TABLE . ", " . DIVISIONS_TABLE . "
                          WHERE ed_event = e_id AND ed_division = d_id AND e_id IN
                                (SELECT e_id FROM " . EVENTS_TABLE . ", " . EVENTDATES_TABLE . ", " . CHAMPIONSHIPS_TABLE . "
                                 WHERE ed_date > NOW() AND e_openSignUps = 1 AND ed_event = e_id AND e_championship = c_id AND c_enabled = 1)
                         ORDER BY ed_date DESC, d_order ASC";

        $result = $db->sql_query($queryDateInfo);
        while($row = $db->sql_fetchrow($result))
        {
            $data[$row['e_id']]['division' . $row['d_order']] = $row;

            if($data[$row['e_id']]['dcount'] < $row['d_order'])
                $data[$row['e_id']]['dcount'] = $row['d_order'];
        }


        foreach($data as $event)
        {
            //need to figure out the dates.
            $postDate = 0;
            for($x = 1; $x <= $event['dcount']; $x++)
            {
                $newDate = strtotime($event['division'.$x]['ed_date']);
                if($postDate == 0)
                    $postDate = $newDate;
                elseif($postDate > $newDate)
                    $postDate = $newDate;
            }

            $postDate = strtotime("-{$properties['cron_openeventstime']} days", $postDate);

            $description = '';

            if($event['t_logo']!='')
                $description = "<img src=\"{$www_path}{$event['t_logo']}\"/> <br/><br/>";


            $description .= "{$lang['TrackLocation']}: {$event['t_location']}. <br/><br/>";

            for($x = 1; $x <= $event['dcount']; $x++)
            {
                $newDate = date("l F j, Y, g:i a",strtotime($event['division'.$x]['ed_date']));
                $description.= $event['division'.$x]['d_title'] == $event['c_title'] ? '' : $event['division'.$x]['d_title'] . ": ";
                $description .= "{$newDate}, {$lang['EventCapacity']}: {$event['division'.$x]['ed_capacity']}. <br/>";
            }

            //Create an empty FeedItem
            $newItem = $feed->createNewItem();

            //Add elements to the feed item
            $newItem->setTitle("{$event['c_title']}, {$event['e_title']}, {$event['t_fullTitle']}");
            $newItem->setLink($www_path . "events.php?mode=entrants&id={$event['e_id']}");
            $newItem->setDate($postDate);
            $newItem->setDescription($description);

            //Now add the feed item
            $feed->addItem($newItem);
        }

        //OK. Everything is done. Now genarate the feed.
        $feed->genarateFeed();
}
else if(isset ($_GET['feed']) && $_GET['feed'] == 'racewins')
{

        //Creating an instance of FeedWriter class.
        $feed = new FeedWriter(RSS2);
        //Setting the channel elements
        //Use wrapper functions for common channel elements
        $feed->setTitle('GRC League Control: Latest Race Winners Feed');
        $feed->setLink($www_path . 'feeds.php?feed=racewins');
        $feed->setDescription('All the latest Race Winners from GRC.');

        //Image title and link must match with the 'title' and 'link' channel elements for valid RSS 2.0
        $feed->setImage('GRC Logo',$www_path . 'feeds.php?feed=racewins',$www_path . '/skins/default/images/email_grc_logo.jpg');

        $data=Array();

        $query = "SELECT pf_drivername, c_title, d_title, e_title, t_fullTitle, ed_date, e_id, c_id, d_id, g_name, c_logoURL, d_logo, t_logo, r_race, c_eventsPerMeeting, user_id
                  FROM ". CHAMPIONSHIPS_TABLE .", " . GAMES_TABLE . ", " . RACERESULTS_TABLE . ", " . EVENTS_TABLE . ", " . DIVISIONS_TABLE . ", " .
                          EVENTDATES_TABLE . ", " . EVENTSIGNUPS_TABLE . ", " . DRIVERNAME_TABLE . ", " . TRACKS_TABLE . "
                  WHERE c_enabled = 1 AND c_game = g_id AND c_id = d_champid AND e_championship = c_id AND r_event = e_id AND r_raceposition = 1 AND e_track = t_id AND
                        es_event = e_id AND es_driver = r_driver AND d_id = es_division AND r_driver = user_id AND ed_division = d_id AND ed_event = e_id
                  ORDER BY ed_date DESC, r_race DESC
                  LIMIT 0, 10";


        $result = $db->sql_query($query);
        while($row = $db->sql_fetchrow($result))
        {
            $row = formatArrayOutput($row);

            //need to figure out the dates.
            $postDate = strtotime($row['ed_date']);
            $postDate = strtotime("+3 hours", $postDate);

            $description = '';

            if($row['t_logo']!='')
                $description = "<img src=\"{$www_path}{$row['t_logo']}\"/> <br/><br/>";
            else if($row['d_logo']!='')
                $description = "<img src=\"{$www_path}{$row['d_logo']}\"/> <br/><br/>";
            else if($row['c_logoURL']!='')
                $description = "<img src=\"{$www_path}{$row['c_logoURL']}\"/> <br/><br/>";

            $eventname = '';
            if($row['d_title'] == $row['c_title'])
                $eventname = "{$row['c_title']}: {$row['e_title']}";
            else
                $eventname = "{$row['c_title']} {$row['d_title']}: {$row['e_title']}";

            if($row['c_eventsPerMeeting'] > 1)
                $eventname .= " {$lang['ResultsRace']} {$row['r_race']}";
                
            $track = $row['t_fullTitle'];
            if($row['c_eventsPerMeeting'] > 1)
                $track .= " {$lang['ResultsRace']} {$row['r_race']}";

            $description .= sprintf($lang['RaceResult' . (($row['e_id'] + $row['user_id'] + $row['r_race']) % 4)], $row['pf_drivername'], $eventname, $row['t_fullTitle']);

            //Create an empty FeedItem
            $newItem = $feed->createNewItem();

            //Add elements to the feed item
            $newItem->setTitle(sprintf($lang['RaceResultTitle' . (($row['c_id'] + $row['user_id'] + $row['r_race']) % 4)], $row['pf_drivername'], $eventname, $track));
            $newItem->setLink($www_path . "championships.php?mode=results&id={$row['c_id']}&race={$row['e_id']}-{$row['d_id']}-{$row['r_race']}");
            $newItem->setDate($postDate);
            $newItem->setDescription($description);

            //Now add the feed item
            $feed->addItem($newItem);
        }

        //OK. Everything is done. Now genarate the feed.
        $feed->genarateFeed();

}
else if(isset ($_GET['feed']) && $_GET['feed'] == 'champions')
{

        //Creating an instance of FeedWriter class.
        $feed = new FeedWriter(RSS2);
        //Setting the channel elements
        //Use wrapper functions for common channel elements
        $feed->setTitle('GRC League Control: Latest Champions Feed');
        $feed->setLink($www_path . 'feeds.php?feed=champions');
        $feed->setDescription('All the latest Champions from GRC.');

        //Image title and link must match with the 'title' and 'link' channel elements for valid RSS 2.0
        $feed->setImage('GRC Logo',$www_path . 'feeds.php?feed=champions',$www_path . '/skins/default/images/email_grc_logo.jpg');

        $data=Array();

        $query = "SELECT pf_drivername, c_title, d_title, hc_title, c_id, g_name, c_logoURL, d_logo, c_lastRace, user_id, d_id
                  FROM " . CHAMPIONSHIPS_TABLE . ", " . GAMES_TABLE . ", " . DIVISIONS_TABLE . ", " .
                           DRIVERNAME_TABLE . ", " . HONOURCATS_TABLE . ", " . HONOURENTRIES_TABLE . "
                  WHERE c_enabled = 1 AND c_game = g_id AND c_id = d_champid AND hc_division = d_id AND
                        hc_id = he_cat AND he_rank = 1 AND he_item = user_id AND hc_cat = 0
                  ORDER BY c_lastRace DESC LIMIT 0, 5";


        $result = $db->sql_query($query);
        while($row = $db->sql_fetchrow($result))
        {
            $row = formatArrayOutput($row);

            //need to figure out the dates.
            $postDate = strtotime($row['c_lastRace']);

            $description = '';

            if($row['d_logo']!='')
                $description = "<img src=\"{$www_path}{$row['d_logo']}\"/> <br/><br/>";
            else if($row['c_logoURL']!='')
                $description = "<img src=\"{$www_path}{$row['c_logoURL']}\"/> <br/><br/>";

            $eventname = '';
            if($row['d_title'] == $row['c_title'])
                $eventname = "{$row['c_title']}";
            else
                $eventname = "{$row['c_title']} {$row['d_title']}";

            $eventname .= " {$row['hc_title']}";

            $description .= sprintf($lang['ChampResult' . (($row['d_id'] + $row['c_id'] + $row['user_id']) % 4)], $row['pf_drivername'], $eventname);

            //Create an empty FeedItem
            $newItem = $feed->createNewItem();

            //Add elements to the feed item
            $newItem->setTitle(sprintf($lang['ChampResult' . (($row['d_id'] + $row['user_id']) % 4)], $row['pf_drivername'], $eventname));
            $newItem->setLink($www_path . "championships.php?mode=honours&id={$row['c_id']}");
            $newItem->setDate($postDate);
            $newItem->setDescription($description);

            //Now add the feed item
            $feed->addItem($newItem);
        }

        //OK. Everything is done. Now genarate the feed.
        $feed->genarateFeed();

}
?>
